package loan.calc.calculator.impl;

import loan.calc.dto.LoanDTO;
import loan.calc.dto.LoanRepaySegmentDTO;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component("repaySegmentDefaultRepaymentDayCalculator")
public class LoanRepaymentSegmentDefaultRepaymentDayCalculator extends AbstractCalculator {

    private static final Integer SORT_CODE = 200;

    @Override
    public Integer calculatorSort() {
        return SORT_CODE;
    }

    @Override
    public String calculatorName() {
        return "调整还款区段默认还款日";
    }

    @Override
    public void calculate(LoanDTO loan) {
        loan.getLoanRepaySegmentList().forEach(loanRepaymentSegment -> doCalculate(loan, loanRepaymentSegment));
    }

    private void doCalculate(LoanDTO loan, LoanRepaySegmentDTO loanRepaymentSegment) {
        Integer defaultRepaymentDay = loanRepaymentSegment.getDefaultRepayDay();
        if (Objects.isNull(defaultRepaymentDay)) {
            defaultRepaymentDay = loan.getStartDate().getDayOfMonth();
        }
        if (defaultRepaymentDay <= 0 || defaultRepaymentDay > 28) {
            defaultRepaymentDay = 15;
        }
        loanRepaymentSegment.setDefaultRepayDay(defaultRepaymentDay);
        printRepaymentSegmentDebugLog(loanRepaymentSegment, "默认还款日:" + defaultRepaymentDay);
    }
}
